<!-- 地图和天气 -->
<script lang='ts' setup>
import * as echarts from 'echarts';
//////
import { Search, CircleCloseFilled } from '@element-plus/icons-vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { shallowRef } from '@vue/reactivity'
import { onMounted, reactive, ref } from 'vue'
import { ElButton, ElDrawer } from 'element-plus'
type EChartsOption = echarts.EChartsOption;
/////
let Amap: any = null;
(window as any)._AMapSecurityConfig = { securityJsCode: '自己申请的密钥', }
let names = reactive({
    startName: '',
    endName: '',
    typeRoad: '驾车',
})
const visible = ref(false)//用来控制天气预报界面的显示与否
let chartDom: any = null
const searchWeather = ref('北京')//天气预报城市名
//搜索值
const searchValue = ref('')
//经纬度指
let locationInfo = reactive({
    lat: '',
    lng: '',
})

let map = shallowRef(null)
//高德安全密钥
onMounted(() => {
    init()
})
//展示天气数据面版
function showForecast() {
    visible.value = true
    queryWeather()
}

//初始化地图
function init() {
    AMapLoader.load({
        key: " ",// 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geolocation', 'AMap.Weather', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Driving', 'AMap.Walking', 'AMap.Riding', 'AMap.Transfer'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        Amap = AMap
        map = new AMap.Map("container", {  //设置地图容器id
            viewMode: "3D",    //是否为3D地图模式W
            zoom: 5,           //初始化地图级别
            center: [105.602725, 37.076636], //初始化地图中心点位置
        });
        location(AMap)
        search(AMap)
        //multiKeyWord(AMap)//多个关键字搜索
        //  queryWeather()
    }).catch(e => {
        console.log(e);
    })
}

//天气数据
const weatherInfo = reactive({
    weatherName: '',
    dayTemp: [''],//白天温度
    nightTemp: [''],//夜晚温度
    week: [''],//日期 周
})
let weatherData: any = []
function queryWeather() {
    //天气查询
    //加载天气查询插件
    Amap.plugin('AMap.Weather', function () {
        //创建天气查询实例
        var weather = new Amap.Weather();
        //执行实时天气信息查询
        weather.getForecast(searchWeather.value, function (err: any, data: any) {
            console.log("weather is :", data.forecasts)
            if (!err) {
                weatherData.value = []
                weatherInfo.weatherName = '',
                    weatherInfo.dayTemp = [''],//白天温度
                    weatherInfo.nightTemp = [''],//夜晚温度
                    weatherInfo.week = [''],//日期 周
                    weatherInfo.weatherName = data.city
                weatherData.value = data.forecasts,
                    data.forecasts.forEach((e: { dayTemp: string, nightTemp: string, week: string }) => {
                        weatherInfo.dayTemp.push(e.dayTemp)
                        weatherInfo.nightTemp.push(e.nightTemp)
                        weatherInfo.week.push("Week" + e.week)
                    });
                initWeather()
            }
        });
    });
}

function initWeather() {
    //使用echarts 渲染天气数据
    setTimeout(() => {
        chartDom = document.getElementById('main')!;
        var myChart = echarts.init(chartDom, {
            renderer: 'svg'
        });
        var option: EChartsOption;
        option = {
            tooltip: {
                trigger: 'axis',
            },
            legend: {},
            toolbox: {
                show: true,
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    dataView: { readOnly: false },
                    magicType: { type: ['line', 'bar'] },
                    restore: {},
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                data: weatherInfo.week
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} °C'
                }
            },
            series: [
                {
                    name: 'Highest',
                    data: weatherInfo.dayTemp,
                    type: 'line',
                    smooth: true,

                },
                {
                    name: 'Lowest',
                    data: weatherInfo.nightTemp,
                    type: 'line',
                    smooth: true,

                },

            ]
        };
        option && myChart.setOption(option);
    }, 0);
}
//路线规划
let driving: any = null
function pathPlaning() {
    if (driving) {
        //调用clear()函数清除上一次结果，可以清除地图上绘制的路线以及路径文本结果
        driving.clear();
    }
    switch (names.typeRoad) {
        case '驾车':
            names.typeRoad = 'Driving'
            break;
        case '骑行':
            names.typeRoad = 'Riding'
            break;
        case '公交':
            names.typeRoad = 'Transfer'
            break;
        case '步行':
            names.typeRoad = 'Walking'
            break;

        default:
            names.typeRoad = 'Driving'
            break;
    }
    console.log("我被调用了", names.typeRoad);
    //构造路线导航类
    driving = new Amap[names.typeRoad]({
        map: map,
        panel: "panel"
    });
    // 根据起终点经纬度规划驾车导航路线
    driving.search([
        { keyword: names.startName, },
        { keyword: names.endName, }
    ], function (status: any, result: any) {
        // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
        if (status === 'complete') {
            console.log('绘制驾车路线完成', +result)
        } else {
            console.log('获取驾车数据失败：' + result)
        }
    });

}
//poi 搜索与提示
function search(AMap: any) {
    //输入提示
    var autoOptions = {
        input: "tipinput"
    };
    AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
        var auto = new AMap.AutoComplete(autoOptions);
        var placeSearch = new AMap.PlaceSearch({
            pageSize: 5, // 单页显示结果条数
            pageIndex: 1, // 页码
            city: "010", // 兴趣点城市
            citylimit: true,  //是否强制限制在设置的城市内搜索
            map: map, // 展现结果的地图实例
            panel: "panel", // 结果列表将在此容器中进行展示。
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });  //构造地点查询类
        auto.on("select", select);//注册监听，当选中某条记录时会触发
        function select(e: any) {
            placeSearch.setCity(e.poi.adcode);
            placeSearch.search(e.poi.name);  //关键字查询查询
        }
    });
}
//多个关键字搜索
function multiKeyWord() {
    Amap.plugin(["AMap.PlaceSearch"], function () {
        var placeSearch = new Amap.PlaceSearch({ //构造地点查询类
            pageSize: 5, // 单页显示结果条数
            pageIndex: 1, // 页码
            city: "010", // 兴趣点城市
            citylimit: true,  //是否强制限制在设置的城市内搜索
            map: map, // 展现结果的地图实例
            panel: "panel", // 结果列表将在此容器中进行展示。
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        //关键字查询
        placeSearch.search(searchValue.value);
    });
}
function multiKey() {
    multiKeyWord()
}
//定位
async function location(AMap: any) {
    AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量
            offset: [10, 20],
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            position: 'RB'
        })
        geolocation.getCurrentPosition(function (status: any, result: any) {
            if (status == 'complete') {
                onComplete(result)
            } else {
                onError(result)
            }
        });

        function onComplete(data: any) {
            console.log("ok", data);
            locationInfo.lat = data.position.lat
            locationInfo.lng = data.position.lng
            console.log("ok", locationInfo);
            // data是具体的定位信息
        }

        function onError(data: any) {
            console.log("err", data);
            // 定位出错
        }
    })

}
//切换天气预报城市
function changes(name: string) {
    searchWeather.value = name
    queryWeather()
}
</script>
<template>
    <div id="container"></div>
    <div id="inputBox">
        <div class="btns_group">
            <el-radio-group v-model="names.typeRoad" size="large">
                <el-radio-button class="btns" label="驾车" @change="pathPlaning()" />
                <el-radio-button class="btns" label="骑行" @change="pathPlaning()" />
                <el-radio-button class="btns" label="公交" @change="pathPlaning()" />
                <el-radio-button class="btns" label="步行" @change="pathPlaning()" />
            </el-radio-group>
        </div>
        <div class="inputs_group">
            <el-input v-model="names.startName" class="w-50 m-2" size="large" placeholder="起始地名" />
            <el-input v-model="names.endName" class="w-50 m-2" size="large" placeholder="终点地名" />
        </div>
        <div class="btns_group">
            <el-button class="btns" type="success" @click="pathPlaning()">确认</el-button>
            <el-button class="btns" type="danger" @click="names.startName = ' '; names.endName = ' '">重置</el-button>
            <el-button class="btns" type="danger" @click="showForecast()">天气信息</el-button>
        </div>
    </div>
    <div id="myPageTop">
        <table>
            <tr>
                <td>
                    <input class="keyInput" v-model="searchValue" id="tipinput" placeholder="请输入关键字："
                        @keyup.enter="multiKey()" @blur="multiKey()" />
                </td>
            </tr>
        </table>
    </div>
    <div id="panel"></div>
    <el-drawer v-model="visible" :show-close="false">
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">WEATHER FORECAST!1</h4>
            <el-button type="danger" @click="close">
                <el-icon class="el-icon--left">
                    <CircleCloseFilled />
                </el-icon>
                Close
            </el-button>
        </template>
        <h2 style="margin-bottom: 15px;margin-left: 30px; color:gray; "> {{
                weatherInfo.weatherName
        }} 天气预报
            <el-input style="margin-left: 15px; width: 150px;" v-model="searchWeather" class="w-50 m-2" size="large"
                placeholder="切换" :suffix-icon="Search" @change="changes(searchWeather)" />
        </h2>
        <div id="main"></div>
    </el-drawer>
</template>
<style lang='scss' scoped>
#main {
    width: 27vw;
    height: 28vw;
    background-color: rgb(252, 250, 250);
}

#container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 100%;
}

#inputBox {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    position: absolute;
    left: 550px;
    bottom: 50px;
    width: 300px;
    height: 200px;
    background-color: rgba(179, 171, 171, 0.781);
    border-radius: 15px;
    z-index: 99999;

    .inputs_group {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 90px;
        padding: 0 10px;
    }

    .btns_group {
        display: flex;
        justify-content: space-evenly;

        .btns {
            border-radius: 10px;
        }
    }
}

#myPageTop {
    position: absolute;
    top: 0;
    left: 200px;
    width: 350px;
    height: 800px;
}

#panel {
    position: absolute;
    max-height: 90%;
    overflow-y: auto;
    top: 60px;
    width: 300px;
}

.keyInput {
    margin-top: 20px;
    margin-left: 20px;
    width: 172px;
    height: 30px;
    border: 1px solid rgb(20, 67, 197);
    border-radius: 5px;
    box-shadow: 1px 1px 5px 1px rgba(58, 58, 99, 0.2);
    font-size: 16px;
}
</style>
